import requests
from lxml import etree
import re

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
}


# 空气质量
def weather_air(text):
    air = re.findall('window.air = (.*?);', text)[0]
    aqi = re.findall('"aqi":(.*?),', air)[0]
    pm25 = re.findall('"pm25":(.*?),', air)[0]
    pm10 = re.findall('"pm10":(.*?),', air)[0]
    so2 = re.findall('"so2":(.*?),', air)[0]
    co = re.findall('"co":(.*?),', air)[0]
    o3 = re.findall('"o3":(.*?),', air)[0]
    no2 = re.findall('"no2":(.*?)}', air)[0]
    data = {
        'aqi': aqi,
        'pm25': pm25,
        'pm10': pm10,
        'so2': so2,
        'co': co,
        'o3': o3,
        'no2': no2
    }
    # print(air)
    # print(data)
    return data


# 空气质量描述
def air_text(tree):
    air_quality = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div[1]/h4/text()')[0]
    air_word = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div[2]/p/text()')[0]
    air_word = air_word.replace("\n", '').replace(' ', '')
    air_advise = tree.xpath('/html/body/div[3]/div[3]/div/div[1]/div/div[4]/p[2]/text()')[0]
    air_advise = air_advise.replace("\n", '').replace(' ', '')
    data = {
        'quality': air_quality,
        'word': air_word,
        'advise': air_advise
    }
    return data


# 空气质量未来7天
def air_day7(tree):
    data = []
    for i in range(7):
        day = tree.xpath(f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[2]/div/div/div[{i + 1}]/div[1]/p[1]/text()')[
            0]
        date = tree.xpath(f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[2]/div/div/div[{i + 1}]/div[1]/p[2]/text()')[
            0]
        aqi = \
            tree.xpath(f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[2]/div/div/div[{i + 1}]/div[3]/span[1]/text()')[
                0]
        txt = \
            tree.xpath(f'/html/body/div[3]/div[3]/div/div[3]/div[1]/div[2]/div/div/div[{i + 1}]/div[3]/span[2]/text()')[
                0]
        obj = {
            'day': day,
            'date': date,
            'aqi': aqi,
            'txt': txt
        }
        data.append(obj)
    return data


# 空气质量
def weatherAirHtml(city, code):
    weather_url = f'https://www.qweather.com/air/{city}-{str(code)}.html'
    try:
        response = requests.get(url=weather_url, headers=headers)
        weather_tree = etree.HTML(response.text)

        air = weather_air(response.text)
        airText = air_text(weather_tree)
        day7 = air_day7(weather_tree)

        data = {
            'air': air,
            'airText': airText,
            'day7': day7
        }
        # print(data)
        return data
    except:
        string = '爬取失敗,请检查输入的参数是否正确'
        print(string)
        return string


# 测试代码
# weatherAirHtml('guangzhou', 101280101)
